import env from './env';
import requestCode from "./code";

const timeout = 30000; //默认请求时间
let retryRequestsQueue = []; //需要重新请求的队列
// let log = require('../utils/log');
// let vConsole = require('../utils/vConsole');


const handleSaveStorage = (accessToken, refreshToken, isNeedReport = false) => {
	try {
		wx.setStorageSync('cisdiAccessToken', accessToken);
		wx.setStorageSync('cisdiRefreshToken', refreshToken);
		if (isNeedReport) {
			// log.info(`新token：${accessToken};新refreshToken：${refreshToken}`);
		}
	} catch (error) {
		console.error("保存token数据报错", error);
	}
};
/**
 * 处理微信的系统报错，直接重新加载整个小程序，为解决用户在访问高峰时，会出现无数据返回
 * 导致不断重新绑定手机号的情况
 */
const handleWxReqErr = err => {
	if (err.errno == 600001 || err.errno == 5 || err.errMsg.indexOf("request:fail") > -1) {
		wx.hideLoading();
		wx.showModal({
			title: '温馨提示',
			content: "当前网络繁忙，请1分钟后再试",
			confirmText: "立即重试",
			complete: (res) => {
				if (res.confirm) {
					wx.restartMiniProgram({
						path: "/pages/workSite/index"
					})
				}
			}
		})
	} else {
		wx.showToast({
			title: err.errno ? `错误码：${err.errno},${err.errMsg}` : err.errMsg,
			icon: 'none',
			duration: 2000
		})
	}
}

const login = (reject) => {
	//重新登录
	wx.login({
		success: (data) => {
			wx.request({
				url: `${env.apiUrl}/zgb/v1/user/login`,
				method: "post",
				data: {
					code: data.code,
					appType: 7,
					authCode: uni.getStorageSync('authCode') || null
				},
				timeout: timeout,
				success: res => {
					if (res.data.code == requestCode.SUCCESS) {
						handleSaveStorage(res.data.data.accessToken, res.data.data
							.refreshToken, true);
						wx.setStorageSync('cisdiHasPhoneNumber', res.data.data
							.hasPhoneNumber);
						retryRequest();
					} else {
						wx.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 2000
						})
						reject();
						retryRequestsQueue = [];
						wx.hideLoading();
						setTimeout(() => {
							uni.navigateBack();
							uni.removeStorageSync('cisdiAccessToken');
							uni.removeStorageSync('cisdiRefreshToken');
						}, 1500)
					}
				},
				fail: loginErr => {
					console.log(loginErr);
					wx.showToast({
						title: "登录接口请求失败",
						icon: 'none',
						duration: 2000
					});
				}
			})
		},
		fail: err => {
			retryRequestsQueue = [];
			console.error(`微信登录请求失败，接口返回值：${JSON.stringify(err)}`);
			handleWxReqErr(err);
			// wx.showToast({
			//   title: err.errno ? `错误码：${err.errno},${err.errMsg}` : err.errMsg,
			//   icon: 'none',
			//   duration: 2000
			// })
		}
	})
}

const refreshToken = (reject) => {
	//刷新token
	wx.request({
		url: `${env.apiUrl}/zgb/v1/user/refreshToken`,
		method: "get",
		data: {
			refreshToken: wx.getStorageSync('cisdiRefreshToken')
		},
		timeout: timeout,
		success: result => {
			if (result.data.code == requestCode.SUCCESS) {
				handleSaveStorage(result.data.data.accessToken, result.data.data.refreshToken);
				retryRequest();
			} else if (result.data.code == requestCode.REFRESH_TOKEN_ERROR) {
				//refreshToken有问题，重新去获取
				wx.removeStorageSync('cisdiAccessToken');
				wx.removeStorageSync('cisdiRefreshToken');
				wx.removeStorageSync('cisdiHwConfig');
				login(reject);
			} else {
				retryRequestsQueue = [];
				reject();
				wx.hideLoading();
				console.error(
					`刷新token失败，请求值：${wx.getStorageSync('cisdiRefreshToken')}，接口返回值：${JSON.stringify(result)}`
				);
				wx.showToast({
					title: result.data.msg,
					icon: 'none',
					duration: 2000
				})
			}
		},
		fail: loginErr => {
			console.log(loginErr);
			wx.showToast({
				title: "刷新token接口请求失败",
				icon: 'none',
				duration: 2000
			})
		}
	})
}


//从请求队列里面重新请求
const retryRequest = () => {
	retryRequestsQueue.forEach(item => {
		request(item.url, item.data, item.method, item.requestLoading, item.requestErrorToast, item.reslove,
			item.reject);
	});
	retryRequestsQueue = [];
}
//打印日志
const printLog = (url, data, res, type = 'info') => {
	if (type == 'error') {
		// log.error(`接口请求失败，请求接口：${url}，请求参数：${JSON.stringify(data)}请求Token：${wx.getStorageSync('accessToken')}`);
		// log.error(`接口返回值：${JSON.stringify(res.data)}`);
		console.error(
			`${url}接口请求失败，请求参数为${JSON.stringify(data)}，返回值${JSON.stringify(res.data)},请求Token为${wx.getStorageSync('cisdiAccessToken')}`
		);
	} else {
		console.log(
			`请求接口：${url}，请求参数：${JSON.stringify(data)}，返回值：${JSON.stringify(res.data)},请求Token：${wx.getStorageSync('cisdiAccessToken')}`
		);
		// log.info(`请求接口：${url}，请求参数：${JSON.stringify(data)}请求Token：${wx.getStorageSync('accessToken')}`);
		// log.info(`接口返回值：${JSON.stringify(res.data)}`);
	}
}

/**
 * requestLoading:请求加载动画，默认为false，产品要求
 * requestErrorToast:请求错误弹框,默认为true
 * retryReslove:Token失效或报错时，重新请求的原始reslove返回
 * retryReject:Token失效或报错时，重新请求的原始reject返回
 */
export const request = (url, data, method, requestLoading, requestErrorToast, retryReslove, retryReject) => {
	if (requestLoading) {
		wx.showLoading({
			title: '加载中',
		})
	}
	return new Promise((reslove, reject) => {
		wx.request({
			url: url,
			method: method,
			data: data,
			timeout: timeout,
			header: {
				'content-type': 'application/json',
				'access-token': wx.getStorageSync('cisdiAccessToken') || ""
			},
			success: (res) => {
				if (res.data.code == requestCode.ACCESS_TOKEN_ERROR) {
					//token有问题,使用refreshToken获取新token
					retryRequestsQueue.push({
						url,
						method,
						data,
						requestLoading,
						requestErrorToast,
						reslove,
						reject
					});
					if (retryRequestsQueue.length <= 1) {
						//控制调刷新token的频率
						refreshToken(reject);
					}
					return;
				}
				printLog(url, data, res);
				if (res.data.code == requestCode.MINI_PROJECT_NOT_EXISTED || res.data.code ==
					requestCode.NO_PROJECT || res.data.code == requestCode
					.MINI_USER_INFO_EMPTY || res.data.code == requestCode.LOGIN_AGAIN) {
					//统一处理后端返回的信息
					if (!wx.getStorageSync('cisdiHasPhoneNumber')) {
						if (wx.getStorageSync('notNeedLogin')) {
							wx.removeStorageSync('notNeedLogin');
						} else {
							wx.setStorageSync('notNeedLogin', true);
							wx.showModal({
								title: '温馨提示',
								content: '当前用户未加入项目，登录查看更多',
								confirmText: "登录",
								cancelText: "取消",
								complete: (res) => {
									if (res.confirm) {
										wx.navigateTo({
											url: '/pages/bind-phone/bind-phone'
										})
									};
								}
							})
							if (retryReject) {
								retryReject(res.data);
							} else {
								reject(res.data);
							}
							return;
						}
					}
				}
				if (res.data.code == requestCode.SUCCESS) {
					//请求成功
					if (retryReslove) {
						retryReslove(res.data);
					} else {
						reslove(res.data);
					}
					if (requestLoading) {
						wx.hideLoading();
					}
				} else {
					//请求返回错误的情况
					if (retryReject) {
						retryReject(res.data);
					} else {
						reject(res.data);
					}
					// printLog(url, data, res, 'error');
					//用户自定义弹框提示
					if (requestErrorToast) {
						wx.showToast({
							title: res.data.msg || res.data.message,
							icon: 'none',
							duration: 2000
						})
					}
				}
			},
			fail: (err) => {
				console.error(
					`微信请求失败，请求接口：${url}，请求参数：${JSON.stringify(data)}请求Token：${wx.getStorageSync('cisdiAccessToken')}`
				);
				console.error(`接口返回值：${JSON.stringify(err)}`);
				if (retryReject) {
					retryReject(err);
				} else {
					reject(err);
				}
				handleWxReqErr(err);
				// wx.showToast({
				//   title: err.errno ? `错误码：${err.errno},${err.errMsg}` : err.errMsg,
				//   icon: 'none',
				//   duration: 2000
				// })
			},
		})
	})
}




// module.exports.request = request;